﻿/*
* Copyright (c) 2010-2012 Tesla Engine Group
* 
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/


using System;
using Tesla.Graphics;
using Tesla.Graphics.Implementation;
using D3D = SlimDX.Direct3D10;
using D3DC = SlimDX.D3DCompiler;

namespace Tesla.Direct3D10.Graphics.Implementation {
    /// <summary>
    /// Concrete Direct3D10 implementation for <see cref="Effect"/>.
    /// </summary>
    public sealed class D3D10EffectImplementation : EffectImplementation {
        private D3D10Renderer _renderer;
        private D3D.Device _graphicsDevice;
        private D3D10EffectTechnique _currentTechnique;
        private byte[] _cachedByteCode; //Potentially shared resource
        private D3D.Effect _effect;
        private String _profileName;
        private D3DC.ShaderFlags _sFlags;
        private D3DC.EffectFlags _eFlags;

        /// <summary>
        /// Gets the D3D10Renderer that created this implementation.
        /// </summary>
        internal D3D10Renderer Renderer {
            get {
                return _renderer;
            }
        }

        /// <summary>
        /// Gets the D3D10 Effect.
        /// </summary>
        internal D3D.Effect D3D10Effect {
            get {
                return _effect;
            }
        }

        /// <summary>
        /// Gets or sets the current technique.
        /// </summary>
        /// <exception cref="System.ArgumentNullException">Thrown if the technique is null.</exception>
        /// <exception cref="System.InvalidOperationException">Thrown if the technique does not belong to the effect.</exception>
        public override IEffectTechnique CurrentTechnique {
            get {
                return _currentTechnique;
            }
            set {
                if(value == null) {
                    throw new ArgumentNullException("Current technique must not be null");
                }

                D3D10EffectTechnique tech = (D3D10EffectTechnique) value;

                if(tech.Parent != this) {
                    throw new InvalidOperationException("Technique does not belong to this effect.");
                }

                _currentTechnique = tech;
            }
        }

        /// <summary>
        /// Creates a new instance of <see cref="D3D10EffectImplementation"/>. Used for cloning.
        /// </summary>
        /// <param name="cloneSource">The implementation source to clone from</param>
        /// <param name="profileName">Name of the shader profile.</param>
        /// <param name="sFlags">The shader flags.</param>
        /// <param name="eFlags">The effect flags.</param>
        internal D3D10EffectImplementation(D3D10EffectImplementation cloneSource, String profileName, D3DC.ShaderFlags sFlags, D3DC.EffectFlags eFlags) {
            _cachedByteCode = cloneSource._cachedByteCode;
            _renderer = cloneSource._renderer;
            _graphicsDevice = cloneSource._graphicsDevice;
            _profileName = profileName;
            _sFlags = sFlags;
            _eFlags = eFlags;
            _effect = D3D.Effect.FromMemory(_graphicsDevice, _cachedByteCode, _profileName, _sFlags, _eFlags, null, null, null);

            //Add to resource tracker
            _renderer.Resources.AddTrackedObject(_effect.ComPointer, this);

            //Clone techniques and parameters
            D3D10EffectTechniqueCollection techniques = cloneSource.Techniques as D3D10EffectTechniqueCollection;
            D3D10EffectParameterCollection parameters = cloneSource.Parameters as D3D10EffectParameterCollection;

            base.SetTechniques(techniques.Clone(_effect, this));
            base.SetParameters(parameters.Clone(_effect));
            _currentTechnique = (D3D10EffectTechnique) base.Techniques[0];
        }

        /// <summary>
        /// Creates a new instance of <see cref="D3D10EffectImplementation"/>.
        /// </summary>
        /// <param name="renderer">The D3D10 renderer.</param>
        /// <param name="shaderByteCode">The compiled shader byte code.</param>
        /// <param name="profileName">Name of the shader profile.</param>
        /// <param name="sFlags">The shader flags.</param>
        /// <param name="eFlags">The effect flags.</param>
        internal D3D10EffectImplementation(D3D10Renderer renderer, byte[] shaderByteCode, String profileName, D3DC.ShaderFlags sFlags, D3DC.EffectFlags eFlags) {
            _cachedByteCode = shaderByteCode;
            _renderer = renderer;
            _graphicsDevice = _renderer.GraphicsDevice;
            _profileName = profileName;
            _sFlags = sFlags;
            _eFlags = eFlags;
            _effect = D3D.Effect.FromMemory(_graphicsDevice, _cachedByteCode, _profileName, _sFlags, _eFlags, null, null, null);

            //Add to resource tracker
            _renderer.Resources.AddTrackedObject(_effect.ComPointer, this);

            int techCount = _effect.Description.TechniqueCount;
            D3D10EffectTechniqueCollection techniques = new D3D10EffectTechniqueCollection();
            D3D10EffectParameterCollection parameters = new D3D10EffectParameterCollection();
            base.SetTechniques(techniques);
            base.SetParameters(parameters);

            for(int i = 0; i < techCount; i++) {
                D3D10EffectTechnique tech = new D3D10EffectTechnique(this, _effect, _effect.GetTechniqueByIndex(i));
                ((D3D10EffectTechniqueCollection) techniques).Add(tech);
            }

            //Set the current technique, the first one by default
            _currentTechnique = (D3D10EffectTechnique) techniques[0];
        }

        /// <summary>
        /// Releases unmanaged resources and performs other cleanup operations before the
        /// <see cref="D3D10EffectImplementation"/> is reclaimed by garbage collection.
        /// </summary>
        ~D3D10EffectImplementation() {
            Dispose(false);
        }

        /// <summary>
        /// Copies this effect, creating a new instance.
        /// </summary>
        /// <returns>Cloned instance of the effect</returns>
        public override EffectImplementation Clone() {
            D3D10EffectImplementation impl =  new D3D10EffectImplementation(this, _profileName, _sFlags, _eFlags);
            impl.ResourceID = base.ResourceID;
            return impl;
        }

        /// <summary>
        /// Releases unmanaged and - optionally - managed resources
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        protected override void Dispose(bool disposing) {
            if(!IsDisposed) {
                if(_effect != null) {
                    if(_renderer != null) {
                        _renderer.Resources.RemoveTrackedObject(_effect.ComPointer);
                    }
                    _effect.Dispose();
                    _effect = null;
                }
                base.Dispose(disposing);
            }
        }
    }
}
